#!/usr/bin/python3
# @Time    : 2018/6/3 下午 14:12:18  
# @Author  : LaoJI

from . import web
from flask import render_template, jsonify, request, flash, redirect, url_for, session
from app.models.teacher import Teacher
from app.models.myclass import MyClass
from sqlalchemy import and_
from app.models.exams import Exam
from flask_login import current_user, login_required
from app.models.user import User
from app.service.mongo_curd import MongoCrud
from app.models.exam_scores import Exam_Score

mycid = 0


@web.route('/class/<cid>/exams', methods=['Get'])
@login_required
def getexam(cid):
    print(cid)
    res = {}
    global mycid
    mycid = cid
    uid = current_user.get_id()
    user = User.query.get(int(uid))
    res["data"] = {
        "nickname": user.nickname,
        "id": user.id,
        "avatar_url": user.avatar_url
    }

    exam = Exam.getAllExamByCid(cid, uid)
    res["exam"] = exam
    # for exam in res:
    #     print('Name %s score is %s' % (exam.title, exam.des_crib))
    return render_template("exams.html", res=res)


@web.route('/class/<eid>/startexam', methods=['Get'])
@login_required
def startexam(eid):
    res = {}
    uid = current_user.get_id()
    user = User.query.get(int(uid))
    res["data"] = {
        "nickname": user.nickname,
        "id": user.id,
        "avatar_url": user.avatar_url
    }
    es = Exam_Score.query.filter(and_(Exam_Score.eid == eid, Exam_Score.sid == uid)).all()
    if len(es) > 0:
        flash("您已经参加过此次考试，还进去干啥啊")
        return redirect(url_for('web.logsuc'))
    res["cid"] = mycid
    result = MongoCrud.get(eid)
    if result["success"]:
        res["examq"] = result["exam"]
    else:
        flash('根本没这个测试啊')
        return redirect(url_for('web.logsuc'))

    # for exam in res:
    #     print('Name %s score is %s' % (exam.title, exam.des_crib))
    return render_template("exam.html", res=res)


@web.route('/class/exam/finish', methods=['POST'])
@login_required
def finishexam():
    res = {}
    uid = current_user.get_id()
    examid = request.form["examid"]
    time = request.form["time"]
    rightans = request.form["rightans"]
    Exam_Score.addExamScore(uid, examid, time, rightans)
    res["success"] = True
    return jsonify(res)
